package cn.itsource.pethome.pet.controller;

import cn.itsource.pethome.basic.util.*;
import cn.itsource.pethome.org.domain.Employee;
import cn.itsource.pethome.org.domain.Shop;
import cn.itsource.pethome.org.service.IShopService;
import cn.itsource.pethome.pet.domain.Pet;
import cn.itsource.pethome.pet.domain.SearchMasterMessage;
import cn.itsource.pethome.pet.query.SearchMasterMessageQuery;
import cn.itsource.pethome.pet.service.ISearchMasterMessageService;
import cn.itsource.pethome.user.domain.User;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 发布寻主信息controller
 */
@RestController
@RequestMapping("/publish")
public class SearchMasterMessageController {
    @Autowired
    private ISearchMasterMessageService searchMasterMessageService;
    @Autowired
    private IShopService shopService;
    /**
     * 发布寻主信息
     * @param searchMasterMessage
     * @return
     */
    @PostMapping("/searchPublish")
    public AjaxResult SearchMasterMessage(@RequestBody SearchMasterMessage searchMasterMessage, HttpServletRequest httpServletRequest){

        try {
            //调用通过token获取用户
            User user = UserContext.getLoginUser(httpServletRequest);
            //把用户id设置进去
            searchMasterMessage.setUser(user);
            //发布寻主信息
            searchMasterMessageService.SearchMasterMessage(searchMasterMessage);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "发布失败！请重试" + e.getMessage());
        }


    }

    /**
     * 查询待处理的寻主信息
     * @return
     */
    @PatchMapping("/loadPendingMessage")
    public PageList<SearchMasterMessage> loadPendingMessage(@RequestBody SearchMasterMessageQuery query){
        //根据登录人获取拥有的店铺对象
        Shop shop = shopService.loadByEmployee(SystemContext.getSystemLoginUser());
        //设置待处理的状态
        query.setState(0);
        //设置店铺id
        query.setShopId(shop.getId());
        return searchMasterMessageService.loadPageByQuery(query);
    }


    /**
     * 处理寻主信息
     * @param pet
     * @return
     */
    @PostMapping("/handlePendingMessage")
    public AjaxResult handlePendingMessage(@RequestBody Pet pet){
        //获取到登录人
        Employee systemLoginUser = SystemContext.getSystemLoginUser();
        //根据登录人查询shop对象
        Shop shop = shopService.loadByEmployee(systemLoginUser);
        //设置shop值(标记该宠物属于哪个门店)
        pet.setShop(shop);
        searchMasterMessageService.handlePendingMessage(pet);
        return new AjaxResult();
    }


}
